package com.zghhost.codedemo.cvparser;

import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author tantion
 */
public class Demo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            File file = new File("/Users/wow/Desktop/resume.txt");//此处提供简历文件
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("username", "yue.yong@zhaopin.com.cn"); //此处使用用户名
            dataMap.put("password", "Zhaopin@789"); //此处使用密码
            dataMap.put("content", encodeFileToBase64(file));
            dataMap.put("filename", file.getName());
            dataMap.put("extractphoto", "0");
            String json = sendPostReq("http://www.cv-parser.com/buyu-api/parse", dataMap);

            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encodeFileToBase64(File file) throws IOException {
        return new String(Base64.encodeBase64(FileUtils.readFileToByteArray(file)), "UTF-8");
    }

    public static String sendPostReq(final String url, final Map<String, String> dataMap) {
        HttpPost httppost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(new Gson().toJson(dataMap), "UTF-8");
            httppost.setEntity(entity);
            httppost.addHeader("Accept", "application/json;charset=UTF-8");
            httppost.addHeader("Content-Type", "application/json;charset=UTF-8");

            HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                return EntityUtils.toString(httpEntity);
            } else {
                System.out.println(httpResponse.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
